<?php
/**
 * Контроллер связей
 * 
 * Управление связями
 * @author Anton Zavidov
 * @package myLiveShop
 */

/**
 * Класс контроллера для управления связями
 *
 */
class ControllerRelation extends Element{
	/**
	 * Констуктор
	 *
	 * @param string $className имя контроллера
	 */
	public function __construct($className=null){
		$this->name='relation';
		parent::__construct($className?$className:__CLASS__);
	}
	/**
	 * Просмотр елемента
	 *
	 */
	public function show($page=1){
		parent::show();
		$settins=$page===false?array():array(
			'pagination'=>array(
				'page'=>$page,
				'show'=>true
			)
		);
		import('model.user');
		import('model.user_to_user');
		$settins['where']="(".DB::apostrof(ModelUser_to_user::TABLE.DOT.ModelUser_to_user::F_USER_ID)."=".Core::user()." OR ".DB::apostrof(ModelUser_to_user::TABLE.DOT.ModelUser_to_user::F_RELATION_ID)."=".Core::user().") AND ".DB::apostrof(ModelUser_to_user::F_MODE)."<>".ModelUser_to_user::S_CONFIRM;
		$list=array();
		$relations=$this->model('user_to_user')->load(
				false,
				array(
					ModelUser_to_user::F_USER_ID,
					ModelUser_to_user::F_RELATION_ID,
					ModelUser_to_user::F_MODE,
					ModelUser::TABLE.DOT.ModelUser::F_NAME
				),
				$settins
			);
		if(is_array($relations)){
		    foreach ($relations as $item) {
		        if(!isset($list[$item['mode']]))$list[$item['mode']]=array();
		        $item['link']=$item[ModelUser_to_user::F_USER_ID]==Core::user()?$item[ModelUser_to_user::F_RELATION_ID]:$item[ModelUser_to_user::F_USER_ID];
		    	$list[$item['mode']][]=$item;
		    }
		}
		$this->view->set('list',$list);
		$this->view->set('orders',$this->model('user_to_user')->load(
				false,
				array(
					ModelUser_to_user::F_USER_ID,
					ModelUser_to_user::F_RELATION_ID,
					ModelUser_to_user::F_MODE,
					'user.name AS user_name'
				),
				array(
				    'where'=>DB::apostrof(ModelUser_to_user::TABLE.DOT.ModelUser_to_user::F_RELATION_ID)."=".Core::user()." AND ".DB::apostrof(ModelUser_to_user::F_MODE)."=".ModelUser_to_user::S_CONFIRM,
				    'join'=>array(array(
				        'table'=>ModelUser::TABLE,
				        'key'=>ModelUser::F_USER_ID,
				        'join_table'=>ModelUser_to_user::TABLE,
				        'join_field'=>ModelUser_to_user::F_USER_ID
				        )
				    )
				)
			));
		$this->view->set('pagination',$this->model('user_to_user')->pagination);
        $this->build();
	}
	/**
	 * стать друзьями
	 *
	 */
	public function friend(){
		Core::mustLogin();
		L($this->name.' Friend');
		$this->findId();
		$result=$this->model('user_to_user')->loadOne(null,array(
		      ModelUser_to_user::F_MODE,
		      ModelUser_to_user::F_RELATION_ID,    
		  ),array(
		  'where'=>$this->findRelation()
		));
		$message=T::_('Error');
		$mode=(int)$result[ModelUser_to_user::F_MODE];
		if($mode===ModelUser_to_user::S_ALIEN){
		    //дружить нельзя потому что вы враги
		    $message=T::_('Friends_error');
		}elseif($mode===ModelUser_to_user::S_CONFIRM){
		    //подтверждение дружбы
		    
		    //усли мне предложили
		    if($result[ModelUser_to_user::F_RELATION_ID]==Core::user()){
    		    $result=$this->model('user_to_user')->save(
    		      array(ModelUser_to_user::F_MODE=>ModelUser_to_user::S_FRIEND),
    		      array(
    		          ModelUser_to_user::F_RELATION_ID =>Core::user(),
    		          ModelUser_to_user::F_USER_ID =>$this->id
    		      )
    		    );
    		    if(!is_array($result))$message=T::_('Friends_ok');
		    }else{
		        //если я предложил уже
		        $message=T::_('Friends_allredy');
		    }
		}elseif($mode===ModelUser_to_user::S_FRIEND){
		    //дружить нельзя потому что вы и так друзья
		    $message=T::_('Friends_now');
		}else{
		    //посылаем заявку на дружбу
		    $result=$this->model('user_to_user')->create(Core::user(),$this->id,ModelUser_to_user::S_CONFIRM);
		    if(!is_array($result))$message=T::_('Friends_confirm');
		}
		Core::redirect(Core::getReferer(),$message);
	}
	/**
	 * Добавить в список врагов
	 *
	 */
	public function alien(){
	    Core::mustLogin();
		L($this->name.' Alien');
		$this->delete(false);
		$result=$this->model('user_to_user')->create(Core::user(),$this->id,ModelUser_to_user::S_ALIEN);
		Core::redirect(Core::getReferer(true),T::_('Alien_ok'));
	}
	/**
	 * строка запроста для поиска
	 *
	 * @return string
	 */
	private function findRelation(){
	    return "(".ModelUser_to_user::F_USER_ID.'='.$this->id.' AND '.ModelUser_to_user::F_RELATION_ID."=".Core::user().")OR(".ModelUser_to_user::F_USER_ID.'='.Core::user().' AND '.ModelUser_to_user::F_RELATION_ID."=".$this->id.")";
	}
	/**
	 * Удаление
	 *
	 * @param boolean не выполнять редирект
	 */
	public function delete($redirect=true){
		Core::mustLogin();
		parent::delete(false);
		$this->findId(true);
		if(!$this->id){
		    $this->show();
		    return;
		}
		$this->model('user_to_user')->delete(false,array('where'=>$this->findRelation()));
		if($redirect)Core::redirect(base64_decode(Vars::_(Core::REFERER)),T::_('Deleted'));
	}
}